package yunjiao.javatutorials.apache.kafka.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Service;
import yunjiao.javatutorials.apache.kafka.model.NotificationEvent;

/**
 * 通知服务消费者
 *
 * @author yangyunjiao
 */
@Service
@Slf4j
public class NotificationEventConsumer {

    @KafkaListener(
            topics = "${app.kafka.topics.notification}",
            groupId = "${app.kafka.consumer-groups.notification-service}",
            containerFactory = "kafkaListenerContainerFactory"
    )
    public void consumeNotificationEvent(NotificationEvent event,
                                         Acknowledgment ack) {
        try {
            log.info(">>> Sending notification: userId={}, type={}",
                    event.getUserId(), event.getType());

            // 发送通知（邮件、短信、站内信等）
            sendNotification(event);

            ack.acknowledge();
            log.info(">>> Notification sent successfully: userId={}, type={}",
                    event.getUserId(), event.getType());

        } catch (Exception e) {
            log.error("Error sending notification: userId={}", event.getUserId(), e);
            // 通知发送失败处理
        }
    }

    private void sendNotification(NotificationEvent event) {
        // 实际的通知发送逻辑
        // 可以集成邮件服务、短信服务、推送服务等
        switch (event.getType()) {
            case NotificationEvent.NotificationType.ORDER_CONFIRMED:
                sendEmailNotification(event);
                break;
            case NotificationEvent.NotificationType.SHIPPING_UPDATE:
                sendSmsNotification(event);
                break;
            default:
                log.warn("Unknown notification type: {}", event.getType());
        }
    }

    private void sendEmailNotification(NotificationEvent event) {
        // 模拟邮件发送
        log.info(">>> Sending email to user: {}, title: {}",
                event.getUserId(), event.getTitle());
    }

    private void sendSmsNotification(NotificationEvent event) {
        // 模拟短信发送
        log.info(">>> Sending SMS to user: {}, content: {}",
                event.getUserId(), event.getContent());
    }
}
